<template>
  <!-- action提交到地址 -->
  <div class="upload-img">
    <el-upload
      accept="image/png, image/jpeg"
      :class="{ disabled: value }"
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-remove="handleRemove"
      :on-preview="handlePreview"
      :http-request="handleUpload"
    >
      <!-- <img v-if="value" :src="value"> -->
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog
      title="预览"
      :visible="isShow"
      @close="isShow = false"
    >
      <img :src="value" width="100%">
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      isShow: false
    }
  },
  computed: {
    fileList: {
      get() {
        return this.value ? [{ url: this.value }] : []
      },
      set() {}
    }
  },
  methods: {
    // 文件移除时的钩子
    handleRemove() {
      // 需要把value清空
      // 子传父，触发input事件。并传递空字符串
      this.$emit('input', '')
    },
    handlePreview() {
      this.isShow = true
    },
    // 上传
    handleUpload({ file }) {
      // file: 选择的图片文件对象
      // 把选择的对象发至腾讯云服务器

      const cos = new COS({
        SecretId: 'AKIDSggSyHBG5lBnAHwqRvviFZfV5PULmtmy',
        SecretKey: '6wasPhDUXXJ2cy5wNdJyNWP5Wkm3vZy8'
      })
      cos.putObject(
        {
          // 桶名
          Bucket: 'jinitaimei-1305128831',
          // 地区
          Region: 'ap-beijing',
          // 文件名
          Key: file.name,
          // 文件对象
          Body: file
        },
        (err, data) => {
          if (err) {
            return this.$message.success('上传失败')
          }
          // 拿到上传成功的图片地址，同步到父组件中
          this.$emit('input', `https://${data.Location}`)
        }
      )
    }
  }
}
</script>

<style lang='scss' scoped>
.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 146px;
  height: 146px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload:hover {
  border-color: #409eff;
}
.el-icon-plus {
  font-size: 60px;
  color: #8c939d;
  text-align: center;
}
.disabled {
  .el-upload {
    display: none;
  }
}
</style>
